import './base64.js';
import VueMethodsDifferent from 'vueMethodsDifferent';

export default {
  install (Vue, option) {
    // 加载该APP的公共方法
    VueMethodsDifferent();

    Vue.prototype.appSource = APP_SOURCE // 版本信息
    Vue.prototype.isDeviceSdk = (APP_SOURCE.appId === 'sdkdaqin')// 是否设备SDK
    /**
     *@describe 获取时间戳
     *@param {String} (dateStr) 日期
     *@return {String} 
    **/
    Vue.prototype.getTimestamp = function (dateStr) {
      var t;
      if (dateStr) {
        var n = dateStr.replace(/-/g, "/");
        t = new Date(n)
      } else t = new Date;

      return t.getTime().toString()
    }
    /**
     *@describe 获取日期
     *@param {String/Number} (timestamp) 时间戳
     *@return {Array} 
    **/
    Vue.prototype.getDateTime = function (timestamp) {
      var t = timestamp ? new Date(parseInt(timestamp)) : new Date;
      var n = t.getFullYear(),
        a = t.getMonth() + 1,
        r = t.getDate(),
        o = t.getHours(),
        i = t.getMinutes(),
        s = t.getSeconds();

      a >= 10 || (a = "0" + a), r >= 10 || (r = "0" + r), o >= 10 || (o = "0" + o), i >= 10 || (i = "0" + i), s >= 10 || (s = "0" + s);

      return [
        n, // yy
        a, // mm
        r, // dd
        n + "-" + a, // yy-mm
        a + "/" + r, // mm/dd
        o + ":" + i, // hh:mm
        n + "-" + a + "-" + r + " " + o + ":" + i + ":" + s, // yy-mm-dd hh:mm::ss
        a + "-" + r + " " + o + ":" + i + ":" + s // mm-dd hh:mm::ss
      ];
    }
    /**
     *@describe 数字格数化
     *@param {String/Number} (money) 数字
     *@param {Number} (pro) 阈值
     *@return {Number} 元
    **/
    Vue.prototype.numberFormat = function (money, pro = 100) {
      money = money ? (parseFloat(money) / pro).toFixed(2) : '0.00';

      let result = '', integer = money.split('.')[0], decimal = money.split('.')[1];

      while (integer.length > 3) {
        result = ',' + integer.slice(-3) + result;
        integer = integer.slice(0, integer.length - 3);
      }
      if (integer) result = integer + result + '.' + decimal;

      return result
    }
    /**
     *@describe 本地存储
     *@param {String} (name) 存储标识
     *@param {Object} (content) 存储的内容
    **/
    Vue.prototype.setStore = (name, content) => {
      if (!name) return;
      if (typeof content !== 'string') {
        content = JSON.stringify(content);
      }
      window.localStorage.setItem(name, content);
    }
    /**
     *@describe 获取本地存储
     *@param {String} (name) 存储标识
     *@return {Object} 存储的内容
    **/
    Vue.prototype.getStore = name => {
      if (!name) return;
      let content = window.localStorage.getItem(name) || '';

      return content && content != 'undefined' ? JSON.parse(content) : '';
    }
    /**
     *@describe 删除本地存储
     *@param {String} (name) 存储标识
    **/
    Vue.prototype.removeStore = name => {
      if (!name) return;
      window.localStorage.removeItem(name);
    }
    /**
     *@describe 获取地址栏参数
     *@param {String} (name) key
    **/
    Vue.prototype.getUrlParam = function (name) {
      var t = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
        n = window.location.search.substr(1).match(t);

      return null != n ? unescape(n[2]) : null
    }
    /**
     *@describe 手机号码格式化
     *@param {String} (phone) 手机号码
    **/
    Vue.prototype.phoneFormat = function (phone) {
      if (!phone) return '--';

      if (phone.length == 7) phone = phone.slice(0, 7) + '****';
      if (phone.length == 8) phone = phone.slice(0, 8) + '***';

      let w = phone.split('');
      w.splice(3, 0, ' ');
      w.splice(8, 0, ' ');
      w = w.join('');

      return w;
    };
    /**
     *@describe 号码等级翻译
     *@param {String} (level) 等级
    **/
    Vue.prototype.filterLevel = function (level) {
      var levelArr = ['', '特级', '', '', '', '', '', ''];
      return levelArr[parseInt(level)];
    };
    /**
     *@describe ajax 
     *@param {String} (url) 请求地址,
     *@param {object} (postData) 请求参数,
     *@param {function} (success) 成功回调函数,
     *@param {boolean|function} (closeLoad) 是否关闭加载层,
     *@param {boolean} (closeBase64) 是否关闭base64编码,
     *@param {function} (fail) 加载失败处理函数,
    **/
    Vue.prototype.AJAX = function (url, postData, success, closeLoad, closeBase64, fail) {
      // data数据格式
      // {
      //     userInfo:{用户信息
      //         'token':'',
      //         'timestamp':'',
      //         'applicationID':'',
      //         'userId':''
      //         'packageName':''
      //     },
      //     param:{//接口参数

      //     }
      // }
      var xhr = new XMLHttpRequest(), layerIndex, _self = this;
      // 加载
      const loading = (type) => {
        switch (type) {
          case 'start':
            !closeLoad && (layerIndex = layer.open({ type: 2, shadeClose: false, shade: 'background-color: rgba(255,255,255,0)' }));
            break;
          case 'end':
            closeLoad ? typeof closeLoad === 'function' && closeLoad() : layer.close(layerIndex);
            break;
        }
      }

      loading('start');

      let params = JSON.parse(JSON.stringify(postData.params || {}));
      let userInfo = JSON.parse(JSON.stringify(postData.userInfo || {}));
      console.log(params)
      //公共参数
      let sendData = Object.assign(userInfo, params)

      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
      xhr.setRequestHeader('Accept', 'application/json,text/javascript;q=0.01');
      xhr.setRequestHeader('AppType', 'KM_APP');

      //xhr send
      const beginXhr = (boryaAuth, xhrData) => {
        xhr.setRequestHeader('boryaAuth', `${boryaAuth}`);
        xhr.send(xhrData);

        var timer = setTimeout(function () {
          clearTimeout(timer);
          loading('end');

          xhr.onreadystatechange = null;
          xhr.abort();

          let ret = {
            msg: "请求超时"
          }

          if (typeof fail === 'function') {
            fail(ret);
          } else _self.errorBubble(ret);
        }, 60 * 1000);

        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            clearTimeout(timer);
            loading('end');

            if (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304)) {
              try {
                var responseText = JSON.parse(xhr.responseText);

                if (responseText.code == '200') {
                  success(responseText)
                } else {
                  if (typeof fail === 'function') {
                    fail(responseText);
                  } else _self.errorBubble(responseText, postData);
                }

              } catch (e) {
                typeof fail === 'function' && fail();
                // _self.errorBubble('数据解析错误');
                alert(e);
              }

            } else {
              typeof fail === 'function' && fail();
              if (xhr.status === 500) {
                _self.errorBubble('服务器异常');
              } else if (xhr.status === 200) {
                _self.errorBubble('服务器响应错误');
              } else if (xhr.status === 404) {
                _self.errorBubble('服务器地址错误');
              } else if (xhr.status === 0 || xhr.status === 502) {
                _self.errorBubble('服务器失联');
              } else {
                _self.errorBubble(xhr.statusText + xhr.status);
              }
            }
          }
        };
      }

      if (url == '/eas/w/share/getInfo' || url == '/eas/w/install/pack') {//分享获取邀请人信息和下载apk包
        beginXhr('', BASE64.encode(JSON.stringify(sendData)));
        return false;
      }

      //加密
      Jsborya.getAuth({
        data: sendData,
        complete: (res) => {
          try {
            let boryaAuth = res.BoryaAuth || res.boryaAuth;

            if (!boryaAuth) {
              throw Error();
            } else {
              sendData = JSON.stringify(sendData);
              if (!closeBase64) {//接口需要base64编码
                sendData = BASE64.encode(sendData);
              }
              if (APP_SOURCE.appType == 1) { // 卡盟app，要将第四个参数换成3
                boryaAuth = boryaAuth.replace(/(.+),(.+),(.+),(.+),(.+),(.+)/, '$1,$2,$3,3,$5,$6');
              }

              beginXhr(boryaAuth, sendData);
            }
          } catch (e) {
            _self.errorBubble('加密获取失败');
          }
        }
      })
    };
  }
}
